﻿
// ReadWriteXMLDlg.cpp: 实现文件
//

#include "pch.h"
#include "framework.h"
#include "ReadWriteXML.h"
#include "ReadWriteXMLDlg.h"
#include "afxdialogex.h"
#include <atlimage.h>


#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// 对话框数据
#ifdef AFX_DESIGN_TIME
	enum { IDD = IDD_ABOUTBOX };
#endif

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CReadWriteXMLDlg 对话框


CReadWriteXMLDlg::CReadWriteXMLDlg(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_READWRITEXML_DIALOG, pParent)
	, m_strCity(_T(""))
	, m_nPeople(0)
	, m_nArea(0)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	m_hThread = NULL;
	m_nIndex = 0;
	m_bReadFinish = FALSE;

	m_nNum = 0;

	m_pBrush = NULL;
}

CReadWriteXMLDlg::~CReadWriteXMLDlg()
{
	CloseHandle(m_hThread);
}

void CReadWriteXMLDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_LIST_INFO, m_ListXMLInfo);
	DDX_Text(pDX, IDC_EDIT_NUM, m_strCity);
	DDX_Text(pDX, IDC_EDIT_DEPARTMENT, m_nPeople);
	DDX_Text(pDX, IDC_EDIT_POST, m_nArea);
	DDX_Control(pDX, IDC_BTN_CREATE, m_btnCreate);
	DDX_Control(pDX, IDC_BTN_READ, m_btnRead);
	DDX_Control(pDX, IDC_BTN_ADDINFO, m_btnAdd);
	DDX_Control(pDX, IDC_BTN_DELETE, m_btnDelete);
	DDX_Control(pDX, IDOK, m_btnCancel);
}

BEGIN_MESSAGE_MAP(CReadWriteXMLDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BTN_ADD, &CReadWriteXMLDlg::OnBnClickedBtnRead)
	ON_BN_CLICKED(IDC_BTN_ADDINFO, &CReadWriteXMLDlg::OnBnClickedBtnAddinfo)
	ON_BN_CLICKED(IDC_BTN_CREATE, &CReadWriteXMLDlg::OnBnClickedBtnCreate)
	ON_BN_CLICKED(IDC_BTN_DELETE, &CReadWriteXMLDlg::OnBnClickedBtnDelete)
	ON_NOTIFY(NM_CLICK, IDC_LIST_INFO, &CReadWriteXMLDlg::OnNMClickListInfo)
	ON_WM_CTLCOLOR()
	ON_WM_TIMER()
END_MESSAGE_MAP()


// CReadWriteXMLDlg 消息处理程序

BOOL CReadWriteXMLDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != nullptr)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	// TODO: 在此添加额外的初始化代码

	m_ListXMLInfo.SetExtendedStyle(m_ListXMLInfo.GetExtendedStyle()| LVS_EX_FULLROWSELECT| LVS_EX_GRIDLINES);

	CRect rect;
	m_ListXMLInfo.GetClientRect(&rect);
	m_ListXMLInfo.InsertColumn(0,_T("城市"), LVCFMT_CENTER, rect.Width()/3);
	m_ListXMLInfo.InsertColumn(1, _T("人口"), LVCFMT_CENTER, rect.Width() / 3);
	m_ListXMLInfo.InsertColumn(2, _T("面积"), LVCFMT_CENTER, rect.Width() / 3);

	unsigned threadID;

	m_hThread = (HANDLE)_beginthreadex(NULL, 0, DisplayPicture, this, 0, &threadID);

	SetTimer(0,3000,NULL);

	CImage Image;
	Image.Load(_T("..\\Bin\\JPG\\1.jpg"));
	CBitmap bitmap;
	bitmap.Attach(Image.Detach());
	m_DefBrush.CreatePatternBrush(&bitmap);

	m_btnCreate.SetBitmaps(IDB_BMP_CREATE, RGB(0, 0, 0));
	m_btnCreate.OffsetColor(CButtonST::BTNST_COLOR_BK_IN, 30);

	m_btnRead.SetBitmaps(IDB_BMP_READ, RGB(0, 0, 0));
	m_btnRead.OffsetColor(CButtonST::BTNST_COLOR_BK_IN, 30);

	m_btnAdd.SetBitmaps(IDB_BMP_ADD, RGB(0, 0, 0));
	m_btnAdd.OffsetColor(CButtonST::BTNST_COLOR_BK_IN, 30);

	m_btnDelete.SetBitmaps(IDB_BMP_DELETE, RGB(0,0,0));
	m_btnDelete.OffsetColor(CButtonST::BTNST_COLOR_BK_IN, 30);

	m_btnCancel.SetBitmaps(IDB_BMP_DELETE, RGB(0, 0, 0));
	m_btnCancel.OffsetColor(CButtonST::BTNST_COLOR_BK_IN, 30);


	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

void CReadWriteXMLDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CReadWriteXMLDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CReadWriteXMLDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}



void CReadWriteXMLDlg::OnBnClickedBtnRead()
{
	// TODO: 在此添加控件通知处理程序代码
	// 先删除所有,再读取
	m_ListXMLInfo.DeleteAllItems();

	// 创建一个XML文档指针
    MSXML2::IXMLDOMDocumentPtr pDoc;
	// 实例化一个文档指针
	HRESULT hr = pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument60));
	if (!SUCCEEDED(hr))
	{
		MessageBox(_T("加载XML文件错误！"));
		return;
	}
	// 加载XML文件
	VARIANT_BOOL Load = pDoc->load((_bstr_t)_T("..\\Bin\\MyTest.xml"));
	if (Load != -1)
	{
		MessageBox(_T("加载XML文件错误！"));
		return;
	}
	// 声明一个元素指针
	MSXML2::IXMLDOMElementPtr pElemNode;
	// 获取元素的信息;selectSingleNode():如果查询到一个或者多个结点，则返回第一个结点。否则返回NULL
	pElemNode = (MSXML2::IXMLDOMElementPtr)(pDoc->selectSingleNode(_T("//China")));

	// 声明一个容器类型,该类型通常用于容纳属性
	MSXML2::IXMLDOMNamedNodeMapPtr pAttrs = NULL;
	// 声明一个结点链表指针,可以增加，或者删除结点
	MSXML2::IXMLDOMNodeListPtr pNodeList = NULL;

	// 声明结点指针
	MSXML2::IXMLDOMNodePtr pAttrItem = NULL;
	// 获取pNodeList指向的子节点
	pElemNode->get_childNodes(&pNodeList);

	long nCount, iCount;
	MSXML2::IXMLDOMElementPtr pCurNode;
	// 获取pNodeList中结点的个数
	pNodeList->get_length(&iCount);

	for (int i = 0; i < iCount; i++)
	{
		// nextNode:获取当前节点和CObList链表很像
		pCurNode = pNodeList->nextNode();
		// getAttribute:获取当前结点的属性集
		CString strPopular = pCurNode->getAttribute(_T("Population"));
		CString strArea = pCurNode->getAttribute(_T("Area"));
		// Gettext:获取属性对应的文本;Puttext():设置文本
		CString strElemText = (_bstr_t)pCurNode->Gettext();
		// 将获取的属性值添加到CListCtrl控件中
		m_ListXMLInfo.InsertItem(i, strElemText);
		m_ListXMLInfo.SetItemText(i,1, strPopular);
		m_ListXMLInfo.SetItemText(i, 2, strArea);
	}
}


void CReadWriteXMLDlg::OnBnClickedBtnAddinfo()
{
	// TODO: 在此添加控件通知处理程序代码
	UpdateData(TRUE);

	MSXML2::IXMLDOMDocumentPtr pDoc;

	HRESULT hr = pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument60));
	if (!SUCCEEDED(hr))
	{
		MessageBox(_T("加载XML文件错误！"));
		return;
	}

	VARIANT_BOOL Load = pDoc->load((_bstr_t)_T("..\\Bin\\MyTest.xml"));
	if (Load != -1)
	{
		MessageBox(_T("加载XML文件错误！"));
		return;
	}

	MSXML2::IXMLDOMElementPtr pElemNode;
	pDoc->raw_createElement((_bstr_t)_T("City"), &pElemNode);
	pElemNode->Puttext((_bstr_t)m_strCity);
	CString strPeople, strArae;
	strPeople.Format(_T("%d"), m_nPeople);
	strArae.Format(_T("%d"), m_nArea);
	pElemNode->setAttribute(_T("Population"), (_bstr_t)strPeople);
	pElemNode->setAttribute(_T("Area"), (_bstr_t)strArae);
	MSXML2::IXMLDOMElementPtr pRoot;
	pRoot = (MSXML2::IXMLDOMElementPtr)(pDoc->selectSingleNode(_T("//China")));
	pRoot->appendChild(pElemNode);
	pDoc->save(_T("..\\Bin\\MyTest.xml"));

	m_ListXMLInfo.DeleteAllItems();

	OnBnClickedBtnRead();
}


void CReadWriteXMLDlg::OnBnClickedBtnCreate()
{
	// TODO: 在此添加控件通知处理程序代码
	// 创建一个文档指针
	MSXML2::IXMLDOMDocumentPtr pDoc;
	MSXML2::IXMLDOMElementPtr pRoot;
	// 实例化文档指针
	HRESULT hr = pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument60));

	if (!SUCCEEDED(hr))
	{
		MessageBox(_T("XML文件创建失败！"));
		return;
	}

	pDoc->raw_createElement((_bstr_t)_T("China"),&pRoot);
	pDoc->raw_appendChild(pRoot,NULL);

	MSXML2::IXMLDOMElementPtr pElemNode;
	pDoc->raw_createElement((_bstr_t)_T("City"), &pElemNode);
	pElemNode->Puttext(_T("上海"));
	pElemNode->setAttribute(_T("Population"),_T("5000"));
	pElemNode->setAttribute(_T("Area"), _T("3000"));
	pRoot->appendChild(pElemNode);

	pDoc->raw_createElement((_bstr_t)_T("City"), &pElemNode);
	pElemNode->Puttext(_T("深圳"));
	pElemNode->setAttribute(_T("Population"), _T("2000"));
	pElemNode->setAttribute(_T("Area"), _T("1000"));
	pRoot->appendChild(pElemNode);

	pDoc->raw_createElement((_bstr_t)_T("City"), &pElemNode);
	pElemNode->Puttext(_T("北京"));
	pElemNode->setAttribute(_T("Population"), _T("8000"));
	pElemNode->setAttribute(_T("Area"), _T("6000"));
	pRoot->appendChild(pElemNode);

	pDoc->raw_createElement((_bstr_t)_T("City"), &pElemNode);
	pElemNode->Puttext(_T("广州"));
	pElemNode->setAttribute(_T("Population"), _T("9000"));
	pElemNode->setAttribute(_T("Area"), _T("7000"));
	pRoot->appendChild(pElemNode);

	pDoc->save(_T("..\\Bin\\MyTest.xml"));

}

void CReadWriteXMLDlg::OnBnClickedBtnDelete()
{
	// TODO: 在此添加控件通知处理程序代码
	MSXML2::IXMLDOMDocumentPtr pDoc;
	HRESULT hr = pDoc.CreateInstance(__uuidof(MSXML2::DOMDocument60));
	if (!SUCCEEDED(hr))
	{
		MessageBox(_T("加载XML文件错误！"));
		return;
	}

	VARIANT_BOOL Load = pDoc->load((_bstr_t)_T("..\\Bin\\MyTest.xml"));
	if (Load != -1)
	{
		MessageBox(_T("加载XML文件错误！"));
		return;
	}

	MSXML2::IXMLDOMElementPtr pRoot;
	pRoot = (MSXML2::IXMLDOMElementPtr)(pDoc->selectSingleNode(_T("//China")));
	
	MSXML2::IXMLDOMNodeListPtr pNodeList;
	pNodeList = pRoot->selectNodes(_T("City"));

	MSXML2::IXMLDOMNodePtr pNode;
	pNode = pNodeList->Getitem(m_nIndex);

	MSXML2::IXMLDOMNodePtr pOldNode;
	pRoot->raw_removeChild(pNode,&pOldNode);

	pDoc->save(_T("..\\Bin\\MyTest.xml"));

	m_ListXMLInfo.DeleteAllItems();

	OnBnClickedBtnRead();
}


void CReadWriteXMLDlg::OnNMClickListInfo(NMHDR* pNMHDR, LRESULT* pResult)
{
	LPNMITEMACTIVATE pNMItemActivate = reinterpret_cast<LPNMITEMACTIVATE>(pNMHDR);
	// TODO: 在此添加控件通知处理程序代码
	CPoint point(pNMItemActivate->ptAction);

	// Select the item the user clicked on.
	UINT uFlags;

	m_nIndex = m_ListXMLInfo.HitTest(point, &uFlags);

	if (uFlags & LVHT_ONITEMLABEL)
	{
		m_ListXMLInfo.SetItem(m_nIndex, 0, LVIF_STATE, NULL, 0, LVIS_SELECTED,
			LVIS_SELECTED, 0);
	}
	
	*pResult = 0;
}


HBRUSH CReadWriteXMLDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
	HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);
	
	if (m_pBrush != NULL)
	{
		return *m_pBrush;
	}
	else
	{
		return m_DefBrush;
	}

	// TODO:  在此更改 DC 的任何特性
	// TODO:  如果默认的不是所需画笔，则返回另一个画笔
	
}

unsigned CReadWriteXMLDlg::DisplayPicture(void* pArguments)
{
	CReadWriteXMLDlg* pDlg = (CReadWriteXMLDlg*)pArguments;

	CFileFind fileFind;
	BOOL bWorking;

	CString strFilePath = _T("..\\Bin\\JPG");
	strFilePath += _T("\\*.*");
	bWorking = fileFind.FindFile(strFilePath);

	while (bWorking)
	{
		bWorking = fileFind.FindNextFile();
		CString strFile = fileFind.GetFileName();
		if (_tcsstr(strFile, _T(".jpg")))
		{
			pDlg->m_arrFileName.Add(strFile);
		}	
	}

	CString strPath, strFileName;
	strPath = _T("..\\Bin\\JPG\\");
	int nCount = pDlg->m_arrFileName.GetCount();
	for (int i = 0; i < nCount; i++)
	{
		strFileName = pDlg->m_arrFileName.GetAt(i);
		CString strFile = strPath + strFileName;
		CImage Image;
		Image.Load(strFile);
		CBitmap* pBitmap = new CBitmap();
		pBitmap->Attach(Image.Detach());
		CBrush* pBrush = new CBrush();
		pBrush->CreatePatternBrush(pBitmap);
		pDlg->m_arrBrush.Add(pBrush);
	}

	pDlg->m_bReadFinish = TRUE;

	return 0;
}

void CReadWriteXMLDlg::OnTimer(UINT_PTR nIDEvent)
{
	// TODO: 在此添加消息处理程序代码和/或调用默认
	int nCount = m_arrFileName.GetCount();
	if (nCount > 0 && m_bReadFinish)
	{
		m_nNum++;
		if (m_nNum >= nCount)
		{
			m_nNum = 0;
		}
		if(m_pBrush != NULL)
			m_pBrush->Detach();
		m_pBrush = m_arrBrush.GetAt(m_nNum);
	}
	CDialogEx::OnTimer(nIDEvent);
}
